import React, { Dispatch } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button, Field, Toast, Form, Notify } from 'react-vant';
import { LoginState, login } from '../../api'
import { useDispatch } from 'react-redux'
export default () => {
	const dispatch = useDispatch()
	const navigate = useNavigate()
	const onFinish = (values: LoginState) => {
		// 异步 action
		// redux-thunk 支持
		dispatch(async (dispatch: Dispatch<any>) => {
			const resp = await login(values);
			const { code, data, mess } = resp.data
			if (code === 200) {
				const { name, tel } = data
				dispatch({ type: 'SET_USER', payload: { isLogin: true, tel, username: name } })
				Notify.show({
					type: 'success',
					message: mess,
					onClose() {
						navigate("/")
					}
				})

			} else {
				Notify.show({ type: 'warning', message: mess })
			}

		})
	};

	return (
		<Form
			onFinish={onFinish}
			footer={
				<div style={{ margin: '16px 16px 0' }}>
					<Button round nativeType="submit" type="primary" block>
						提交
					</Button>
				</div>
			}
		>
			<Form.Item
				name="tel"
				label="手机号"
				rules={[{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确手机号' }]}
			>
				<Field placeholder="请输入手机号" />
			</Form.Item>


		</Form>
	);
};
